<template>
    <transition name="fide">
        <div class="back-scroll-top" :style="{ right: right + 'px', bottom: bottom + 'px' }" @click.stop="toScrollTop" v-show="showBackTop">
            <div v-if="!$slots.default" class="back-top-btn">
                <i class="iconfont icon-shangchuan"></i>
            </div>
            <slot v-else></slot>
        </div>
    </transition>
</template>

<script>
    /**
     * 回到顶部组件
     */
    export default {
        props: {
            areaId: {       // 滚动容器的id
                type: String,
                required: true
            },
            right: {        // 右边的距离
                type: Number,
                default: 50
            },
            bottom: {       // 底部的距离
                type: Number,
                default: 50
            },
            showHeight: {   // 滚动到指定位置显示
                type: Number,
                default: 100
            },
            duration: {     // 滚动到顶部的时间
                type: Number,
                default: 200
            }
        },
        data(){
            return {
                scrollArea: null,   //滚动容器
                showBackTop: false, //是否显示按钮
                timer: null,        
                isOk: true
            }
        },
        mounted(){
            this.init();
        },
        beforeDestroy(){
            this.scrollArea.removeEventListener('scroll', this.onScroll);
        },
        methods: {
            init(){
                this.scrollArea = document.querySelector('#' + this.areaId);
                this.scrollArea.addEventListener('scroll', this.onScroll);
            },
            onScroll(){ //监听容器滚动事件
                if(!this.isOk) return;
                this.isOk = false;
                this.timer = setTimeout(() => {
                    let scrollTop = this.scrollArea.scrollTop;
                    this.showBackTop = this.scrollArea.scrollTop > this.showHeight ? true : false;
                    this.isOk = true;
                }, 1000/60);
            },
            toScrollTop(){  //回到顶部
                this.$utils.CommonUtils.toTop(this.scrollArea, 0, this.duration);
            }
        }
    }
</script>

<style lang="less">
    .back-scroll-top{
        position: absolute;
        z-index: 1200;
    }
</style>

